<?php

namespace app\admin\controller;

use app\admin\model\GroupMenu;
use app\admin\model\GroupNode;
use app\common\constants\MenuConstant;
use app\common\controller\AdminController;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\common\service\MenuService;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="菜单管理")
 */
class Menu extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new GroupMenu();
    }

    public function list(): Json
    {
        //菜单服务类
        $menuService = new MenuService($this->uid, $this->appName, $this->groupId);
        $menuList    = $menuService->getMenuTree(true);
        return $this->success($menuList);
    }

    /**
     * @NodeAnnotation (title="新增")
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $pid = $request->post('pid', 0);
        if ($pid) {
            $pMenu = $this->model->getPidMenu($pid);
            if (!$pMenu) return $this->error('父级菜单不存在！');
        }
        $post = $request->post();
        if (!empty($this->groupId)) $post['group_id'] = $this->groupId;
        if ($post['menu_type'] != MenuConstant::TYPE_CATALOG) {
            if (!$post['api']) return $this->error('接口地址不能为空！');
        }
        try {
            $this->sceneValidate($post, 'add');
            $this->model->transaction(function () use ($post, &$save)
            {
                $save = $this->model->save($post);
            });
            // 添加监听
            event('TriggerUpdateMenu', ['uid' => $this->uid, 'app' => $this->appName]);
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        if (!$save) return $this->error('新增失败');
        return $this->success('新增成功');
    }

    /**
     * @NodeAnnotation (title="编辑")
     */
    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require|integer'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) return $this->error('数据不存在！');
        $post = $request->post();
        try {
            $this->model->transaction(function () use ($post, $row)
            {
                $row->save($post);
            });
            // 添加监听
            event('TriggerUpdateMenu', ['uid' => $this->uid, 'app' => $this->appName]);
        } catch (\Exception $e) {
            return $this->error('保存失败:' . $e->getMessage());
        }
        return $this->success('保存成功');
    }

    /**
     * @NodeAnnotation (title="字段修改")
     */
    public function modify(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id'    => 'require|integer',
        ];
        $this->validate($post, $rule);
        $row  = $this->model->find($post['id']);
        if (!$row) return $this->error('数据不存在');
        try {
            $this->model->transaction(function () use ($post, $row)
            {
                $row->save([
                                   $post['field'] => $post['value'],
                           ]);
            });
            // 添加监听
            event('TriggerUpdateMenu', ['uid' => $this->uid, 'app' => $this->appName]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**
     * @NodeAnnotation (title="删除")
     */
    public function del(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require'
        ];
        $this->validate($post, $rule);
        $ids = explode(',', $post['id']);
        $row = $this->model->whereIn('id', $ids)->select();
        empty($row) && $this->error('数据不存在');
        try {
            foreach ($ids as $id) {
                $row = $this->model->with('authMenu')->find($id);
                if ($row) $row->together(['authMenu'])->delete(true);
            }
            // 添加监听
            event('TriggerUpdateMenu', ['uid' => $this->uid, 'app' => $this->appName]);
        } catch (\Exception $e) {
            return $this->error('删除失败' . $e->getMessage() . $e->getLine());
        }
        return $this->success('删除成功');
    }
}